const express = require("express");
const url = require("url");
const router = express.Router();

const mongoose = require("../model/core");
const { formatTime, unixToDay, unixToYearAndMonth } = require("../model/tools");
const FocusModel = require("../model/focusModel");
const NavModel = require("../model/navModel");
const ArticleCateModel = require("../model/articleCateModel");
const ArticleModel = require("../model/articleModel");
const SettingModel = require("../model/settingModel");

router.use(async (req, res, next) => {
    const pathname = url.parse(req.url).pathname;

    // 获取公共的数据
    const navResult = await NavModel.find({ position: 2 }).sort({ sort: 1 });

    req.app.locals.navList = navResult;
    req.app.locals.pathname = pathname;
    req.app.locals.formatTime = formatTime;
    req.app.locals.unixToDay = unixToDay;
    req.app.locals.unixToYearAndMonth = unixToYearAndMonth;

    req.app.locals.site_title = "2020北京车展";
    req.app.locals.site_keywords = "2020北京车展";
    req.app.locals.site_description = "2022（第十六届）北京国际汽车展览会（Auto China 2022）将在北京中国国际展览中心新馆和中国国际展览中心老馆举行。";

    next();
})

router.get("/", async (req,res)=>{
    // 1. 轮播图
    const focusResult = await FocusModel.find({ type: 1 }).sort({ sort: -1 });
    // 2. 展馆平面图
    const areaPlanList = await ArticleModel.find({ cid: mongoose.Types.ObjectId("68935d377420ff1578e6972f") }).limit(2).sort({ sort: -1 });
    // 3. 展会新闻
    const topNewsList = await ArticleModel.find({ cid: mongoose.Types.ObjectId("6890ba40befbd064a0446c42") }, "title").limit(4).sort({ sort: -1 });
    // 3. 推荐新闻
    const bestNewsList = await ArticleModel.find({ is_best: 1 }).limit(4).sort({ sort: -1 });
    // 5. 获取系统信息
    const settingResult = await SettingModel.find({});
    console.log(`areaPlanList`, areaPlanList);

    res.render("default/index.html", {
        focusList: focusResult,
        areaPlanList,
        topNewsList,
        bestNewsList,
        site_title: settingResult[0].site_title,
        site_keywords: settingResult[0].site_keywords,
        site_description: settingResult[0].site_description
    });
})

router.get("/overview.html",(req,res)=>{
    res.render("default/overview.html", {
        site_title: "2020北京车展-展会概况",
        site_keywords: "2020北京车展-展会概况",
        site_description: "2022（第十六届）北京国际汽车展览会（Auto China 2022）将在北京中国国际展览中心新馆和中国国际展览中心老馆举行。"
    });
})

router.get("/news.html", async (req,res)=>{
    let page = req.query.page || 1;
    let cid = req.query.cid;
    let pageSize = 8;
    let json = {};  // 条件

    // 获取新闻中心的子分类
    if (cid) {
        json = Object.assign(json, { cid: mongoose.Types.ObjectId(cid) });
    } else {
        const cateResult = await ArticleCateModel.find({ pid: mongoose.Types.ObjectId("6890b1c0c1108746381571e6") });
        let tempArr = [];
        cateResult.forEach((value) => {
            tempArr.push(value._id);
        })
        json = Object.assign(json, { cid: { $in: tempArr } });
    }

    let result = await ArticleModel.aggregate([{
        $lookup: {
            from: "article_cate",
            localField: "cid",
            foreignField: "_id",
            as: "cate"
        }
    }, {
        $match: json
    }, {
        $sort: { add_time: -1 }
    }, {
        $skip: (page - 1) * pageSize
    }, {
        $limit: pageSize
    }]);
    let count = await ArticleModel.countDocuments(json);
    res.render("default/news.html", {
        newsList: result,
        totalPages: Math.ceil(count/pageSize),
        page: page,
        cid
     });
})

router.get("/content_:id.html", async (req,res)=>{
    const id = req.params.id;
    const result = await ArticleModel.find({ _id: id });
    res.render("default/news_content.html", {
        list: result[0],
        site_title: result[0].title,
        site_keywords: result[0].keywords,
        site_description: result[0].description
    });
})

router.get("/services.html", async (req,res)=>{
    // 获取展会服务下面的信息，如果可以循环
    // 方式一 统一获取（不适用）
    /* const result = await ArticleCateModel.aggregate([{
        $lookup: {
            from: "article",
            localField: "_id",
            foreignField: "cid",
            as: "articleList"
        }
    }, {
        $match: { pid: mongoose.Types.ObjectId("6890b714e2ddad73a073aecc") }
    }, {
        $sort: { sort: -1 }
    }]);
    console.log(`result==`, result); */

    // 方式二 单独获取
    // 资料下载
    const list1 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("6890c46cd55e2144a420bb57") }, "title link");
    // 票务信息
    const list2 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("6890c460d55e2144a420bb53") }, "title link");
    // 交通信息
    const list3 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("68935d487420ff1578e69733") }, "title link");
    // 平面图
    const list4 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("68935d377420ff1578e6972f") }, "title link");
    // 同期活动
    const list5 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("689446d65c3d845e80dc0e4b") }, "title link");
    // 周边服务
    const list6 = await ArticleModel.find({ cid: mongoose.Types.ObjectId("68935d5f7420ff1578e69737") }, "title link");
    res.render("default/services.html", { list1, list2, list3, list4, list5, list6 });
})

router.get("/contact.html",(req,res)=>{
    res.render("default/contact.html");
})

 module.exports = router